var utils = require('../../../utils/util.js')
var c = require('../../../utils/config.js')
var countdown = 60;
Page({
  data: {
    data: [],
    img_url: c.img_url,
    totalMoney: 0,
    totalNums: 0,
    allChecked: true,
    userinfo: [],
    setphone: {
      phone: "",
      code: "",
      disabled: "",
      codemsg: "获取验证码"
    }
  },
  onLoad: function (options) {
  },
  onShow: function () {
    this.getData();
    this.setData({
      userinfo: wx.getStorageSync("userinfo"),
    })
  },
  //获取api数据
  getData: function () {
    var that = this;
    var token = wx.getStorageSync("userinfo").wap_token;
    var data = {
      url: "/v1/Ordercart/lists",
      goods_type: 0,
      token: token,
    };
    utils.request(data).then(function (res) {
      if (res.code == 0) {
        var data = res.data;
        var totalMoney = 0;
        var totalNums = 0;
        data.forEach((item, index) => {
          data[index]['checked'] = true;
          totalMoney += data[index].nums * data[index].price;
          data[index]['Leftdraw'] = 0;
          totalNums++;
        })
        that.setData({
          data: data,
          totalMoney: totalMoney,
          totalNums: totalNums
        });
      } else {

      }
    });
  },
  // 提交购物车数据
  submit: function () {
    let goods_ids = ''
    for (let index in this.data) {
      if (this.data[index]['checked']) {
        goods_ids += this.data[index]['id'] + '|' + this.data[index]['nums'] + ','
      }
    }
    goods_ids = this.my.rtrim(goods_ids, ',')
    this.$store.commit('setCartGoodsIds', goods_ids)
    this.$store.commit('setCartTotalMoney', this.totalMoney)
    this.$router.push('/clearing');
  },
  // 统计总计
  countTotal: function () {
    let money = 0
    let num = 0
    for (let index in this.data.data) {
      let item = this.data.data[index]
      if (item.checked) {
        money += item.nums * item.price
        num++
      }
    }
    money = parseFloat(money);
    this.setData({
      totalMoney: money,
      totalNums: num
    })
  },
  // 减少数量
  LessNum: function (e) {
    var k = e.currentTarget.dataset.k;
    var v = e.currentTarget.dataset.v;
    var data = this.data.data;
    if (v.nums <= 1) {
      wx.showToast({
        title: '不能少于1',
        icon: 'none',
      })
    } else {
      var data = this.data.data;
      data[k]['checked'] = true
      data[k]['nums'] = v.nums - 1
      this.setData({
        data: data
      })
    }
    this.countTotal()
  },
  // 添加数量
  addNum: function (e) {
    var k = e.currentTarget.dataset.k;
    var v = e.currentTarget.dataset.v;
    var data = this.data.data;
    data[k]['checked'] = true
    data[k]['nums'] = v.nums + 1
    this.setData({
      data: data
    })

    this.countTotal()
  },
  // 勾选当前
  chooseData: function (e) {
    var k = e.currentTarget.dataset.k;
    var data = this.data.data;
    data[k]['checked'] = data[k]['checked'] ? false : true;
    this.setData({
      data: data
    })
    this.isAllChecked()
    this.countTotal()
  },
  // 移除当前
  removeData: function (k) {
    MessageBox.confirm('确定执行此操作?').then(action => {
      this.data.splice(this.data[k], 1)
      this.isAllChecked()
      this.countTotal()
    })
  },
  // 验证是否全选
  isAllChecked: function () {
    let checked = false
    this.data.data.forEach((item, index) => {
      if (item['checked']) {
        checked = true
      }
    })
    this.setData({
      allChecked: checked
    })

  },
  // 选择全部
  chooseAll: function (e) {
    var val = e.currentTarget.dataset.checked;
    var checked = val ? false : true
    var data = this.data.data;
    data.forEach((item, index) => {
      data[index]['checked'] = checked
    })
    this.setData({
      allChecked: checked,
      data: data
    })
    this.isAllChecked()
    this.countTotal()
  },
  submit: function () {
    var data = this.data.data;
    var arr = [];
    var totalPoint = 0;
    data.forEach((item, index) => {
      if (data[index]['checked']) {
        var arr1 = { "title": item.goods_name + item.attr_name, "nums": item.nums, "price": item.price, id: item.id, pic: item.pic };
        arr.push(arr1);
        totalPoint += item.use_money_dj * item.nums;
      }
    })
    arr = JSON.stringify(arr);
    var goodsExt = { goods_type: data[0].goods_type, totalNums: this.data.totalNums, totalMoney: this.data.totalMoney, totalPoint: totalPoint };
    goodsExt = JSON.stringify(goodsExt);

    if (arr == "[]") {
      wx.showToast({
        title: '必须选择一件商品!',
        icon: "none"
      })
      return false;
    }
    wx.navigateTo({
      url: '/pages/shop/confirmorder/index?orderGoods=' + arr + "&goodsExt=" + goodsExt,
    })
  },
  delCart: function (e) {
    var id = e.currentTarget.dataset.id;
    var that = this;
    wx.showModal({
      title: '提示',
      cancelText: '取消',
      confirmText: '确定',
      content: '是否从购物车移除该商品？',
      success: function (res) {
        if (res.confirm) {
          var token = wx.getStorageSync("userinfo").wap_token;
          var data = {
            url: "/v1/Ordercart/edit",
            goods_price_id: id,
            token: token,
            nums: 0
          };
          utils.request(data).then(function (res) {
            if (res.code == 0) {
              utils.sucMsg("删除成功");
              that.getData();
            } else {

            }
          });
        } else if (res.cancel) {

        }
      }
    })
  },
  //以下是登录方法================================================================================================================
  editPhone: function (e) {
    this.setData({
      phone: e.detail.value
    })

  },
  editCode: function (e) {
    this.setData({
      code: e.detail.value
    })

  },
  getCode: function (e) {
    var that = this;
    var phone = this.data.phone;
    var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
    if (phone == "" || !myreg.test(phone)) {
      wx.showToast({
        title: '手机号有误！',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    var data = {
      url: "/comv1/comcodephone/getcode",
      type: "newtel",
      phone: phone
    };
    utils.request(data).then(function (res) {
      if (res.code == 0) {
        that.setTime();
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 1500
        })
      }
    });


  },
  bindPhone: function () {
    var phone = this.data.phone;
    var code = this.data.code;
    var openid = wx.getStorageSync('openId');
    var data = {
      url: "/v1/user/add",
      openid: openid,
      type: 0,
      phone: phone,
      code: code
    };
    utils.request(data).then(function (res) {
      if (res.code == 0) {
        wx.setStorageSync("userinfo", res.data)
        wx.showToast({
          title: "绑定成功",
          icon: 'none',
          duration: 1500
        });
        wx.navigateTo({
          url: '/pages/cart/cart',
        })

      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 1500
        })
      }
    });
  },
  setTime: function () {//验证码
    var that = this;
    var setphone = this.data.setphone;
    if (countdown == 0) {
      setphone.disabled = "";
      setphone.codemsg = "获取验证码";
      this.setData({
        setphone: setphone
      })
      countdown = 60;
      return false;
    } else {
      setphone.disabled = true;
      setphone.codemsg = "重新发送(" + countdown + ")"
      this.setData({
        setphone: setphone
      })
      countdown--;
    }
    setTimeout(function () {
      that.setTime();
    }, 1000);
  },
  starttouch: function (e) {
    this.setData({
      start: e.changedTouches[0].clientX
    })
  },
  endtouch: function (e) {
    let i = e.currentTarget.dataset.index;
    let start = this.data.start;
    let end = e.changedTouches[0].clientX;
    let str = "data[" + i + "].Leftdraw"
    if (start > end) {
      this.setData({
        [str]: -240
      })
    } else {
      this.setData({
        [str]: 0
      })
    }
  }
})
